<?php

class SubscribeController extends Controller
{

	public function filters()
	{
		return array(
			'accessControl',
		);
	}
	public function accessRules()
	{
		return array(
			array('allow', 
				'actions'=>array('index','cafeOwner'),
				'roles'=>array('cafeOwner'),
			),
			array('allow', 
				'actions'=>array('cafeOwnerPay'),
				'users'=>array('@'),
			),
			array('allow', 
				'actions'=>array('cafeOwnerIpn','cafeOwnerSuccess'),
				'users'=>array('*'),
			),
			array('deny',
				'users'=>array('*'),
			),
		);
	}

	public function actionCafeOwner()
	{
		$user=Yii::app()->user;
		$criteria=new CDbCriteria();
		$criteria->compare('ownerId',$user->id);
		
		$shops=CoffeeShop::model()->findAll($criteria);
		$this->render('cafeOwner',array('shops'=>$shops,'shopsData'=>new CActiveDataProvider('CoffeeShop', array(
			'criteria'=>$criteria,
		))));
	}

	public function actionCafeOwnerIpn()
	{
		$p=Yii::app()->paypal;
		if ($p->validateIpn()) {
			$payment=new MCRPaypalTransaction('ipn');
			foreach($payment->getSafeAttributeNames() as $att){
				if(isset($_POST[$att])){
					$payment->$att=$_POST[$att];
				}
			}
			if($payment->save()){
				$p->log('Payment (MCR) Saved to DB');
				$data=$payment->custom;
				if($data){
					$data=split('\\.', $data);
					if($data[0]=='cafeOwner'){
						$this->_subscribeCafeOwner($payment, intval($data[1]));
					}
				}				
			}else{
				$p->log('Payment (MCR) NOT Saved to DB: '.print_r($payment->getErrors(),true));
			}
		}
	}

	public function actionCafeOwnerPay()
	{
		$shopId=intval($_GET['id']);
		$shop=CoffeeShop::model()->findByPk($shopId);
		if(!$shop){
			throw new CHttpException(404,'Shop not found');
		}
		$p=Yii::app()->paypal;
		//$base='http://220.244.248.148:8080/yiiapp/MelbourneCoffeeReview3/index-test.php/subscribe/';
		$p->returnUrl=$this->createAbsoluteUrl('cafeOwnerSuccess');
		$p->cancelUrl=$this->createAbsoluteUrl('index');
		$p->notifyUrl=$this->createAbsoluteUrl('cafeOwnerIpn');
		$p->itemName='MCR Subscribe';
		$p->custom='cafeOwner.'.$shop->id;
		$price=GlobalConfig::getByKey('CAFE_SUBSCRIPTION_FEE_YEAR',0);
		$priceList=array($price=>'One Year ($'.$price.')');
		$this->render('cafeOwnerPay',array('p'=>$p,'shop'=>$shop,'priceList'=>$priceList));
	}
	
	public function actionCafeOwnerSuccess()
	{
		if(Yii::app()->user->checkAccess('cafeOwner')){
			$url=$this->createUrl('subscribe/cafeOwner');
			Yii::app()->clientScript->registerScript("redirect",
			'setTimeout("window.location = \''.$url.'\'",4000)');
		}
		$this->render('success');
	}
	
	
	private function _subscribeCafeOwner($payment,$shopId){
		$subscribe=new CafeOwnerSubscribe('ipn');
		$subscribe->shopId=$shopId;
		$subscribe->txn_id=$payment->txn_id;
		$now=time();
		$period=1;
		$subscribe->startDate=$now;
		$subscribe->endDate=$now + $period * 60 * 60 * 24 * 366;
		$subscribe->save();
	}
}